
#ifndef _C_TIMERS_H_
#define _C_TIMERS_H_

#include <cTools/Common.h>
#include <cTools/List.h>
#include <cTools/Thread.h>
#include <cTools/Mutex.h>

struct _C_Timer_Manager;
struct _C_Timer;

typedef void (*C_Timer_Handler_t)(struct _C_Timer*);

typedef unsigned int C_Timer_Id_t;

#define C_TIMER_ID_INVALID (0)

typedef struct _C_Timer
{
	/** Id assigned by the C_Timer_Manager **/
	C_Timer_Id_t		Id;
	/** Expiration callback **/
	C_Timer_Handler_t	Handler;
	/** User defined pointer **/
	void*				User;
	/** User defined timer id **/
	unsigned int		UserId;
	/** Timer duration **/
	long				Duration;
	/** Set false if single shot **/
	C_Bool_t			Periodic;
	/** Expiration timestamp **/
	struct timeval		Timestamp;
} C_Timer;

typedef C_Timer* C_Timer_Ptr;

C_Timer_Ptr
C_Timer_New_From(const C_Timer_Ptr);

void
C_Timer_Init(C_Timer_Ptr, long duration, C_Timer_Handler_t, C_Bool_t periodic);

void
C_Timer_Init_From(C_Timer_Ptr, const C_Timer_Ptr);

void
C_Timer_Set_User_Data(C_Timer_Ptr, void*, unsigned int);

typedef struct _C_Timer_Manager
{
	C_Thread		Thread;
	C_Timer_Id_t	Id;
	C_Mutex_Ptr		Mutex;
	C_List_Ptr		Timers;
	long			Delay;
} C_Timer_Manager;

typedef C_Timer_Manager* C_Timer_Manager_Ptr;

void
C_Timer_Manager_Init(C_Timer_Manager_Ptr);

void
C_Timer_Manager_Cleanup(C_Timer_Manager_Ptr);

void
C_Timer_Manager_Run(C_Thread_Ptr);

void
C_Timer_Manager_Lock(C_Timer_Manager_Ptr);

void
C_Timer_Manager_Unlock(C_Timer_Manager_Ptr);

C_Error_t
C_Timer_Manager_Start(C_Timer_Manager_Ptr, C_Timer_Ptr);

C_Error_t
C_Timer_Manager_Stop(C_Timer_Manager_Ptr, C_Timer_Id_t);

C_Error_t
C_Timer_Manager_Schedule(C_Timer_Manager_Ptr, C_Timer_Ptr);

void
C_Timer_Manager_Process(C_Timer_Manager_Ptr);


void
C_Sleep(long ms);

#endif
